﻿<template>
  <l-layout class="l-tab-page erpCase custmer" v-show="!lr_loadPage">
    <l-panel v-if="!showDetails">
      <template #title>
        <div>{{ $t("客户列表") }}</div>
        <div style="width: 560px">
          <div class="ml-8" style="float: right">
            <l-tool-btns
              :hasRefresh="false"
              @setting="lr_handleSettingTable"
              @click="handleAdd()"
            >
              <el-button-group>
                <el-button
                  v-if="lr_hasPageAuth('AddOpens', 'buttons')"
                  size="mini"
                  @click="handleAddOpens"
                  type="primary"
                  >{{ $t("加入公海") }}</el-button
                >
              </el-button-group>
              <l-excel-btns></l-excel-btns>
            </l-tool-btns>
          </div>
        </div>
      </template>
      <template #toolLeft>
        <l-query2
          :items="queryItems"
          :formData="queryData"
          :loading="tableLoading"
          @search="handleSearch"
        >
          <template #f_Type>
            <l-select :options="f_TypeOptions" v-model="queryData.f_Type" />
          </template>
          <template #f_Source>
            <l-select :options="f_SourceOptions" v-model="queryData.f_Source" />
          </template>
          <template #f_CreateDate>
            <el-date-picker
              v-model="queryData.f_CreateDate"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </el-date-picker>
          </template>

          <template #f_Name>
            <el-input
              v-model="queryData.f_Name"
              :placeholder="$t('please enter关键词')"
            />
          </template>
        </l-query2>
      </template>
      <l-table
        isMultiSelect
        ref="mainTable"
        :loading="tableLoading"
        :columns="lr_getPageColumns(columns)"
        row-key="f_Id"
        :dataSource="tableData"
        :isPage="true"
        :pageTotal="tableTotal"
        :tablePage.sync="tableCurrentPage"
        @loadPageData="turnTablePage"
      >
        <l-table-btns
          :btns="tableBtns"
          :btnNum="5"
          @click="lr_handleTableBtnClick"
        />
      </l-table>
    </l-panel>
    <!-- Details查看 -->
    <transition name="el-zoom-in-center">
      <l-panel v-if="showDetails">
        <template #title>
          <el-page-header
            @back="
              {
                showDetails = false;
              }
            "
            :content="$t(show_name)"
          />
        </template>

        <DetailForm ref="detailForm"></DetailForm>
      </l-panel>
    </transition>

    <!--表单-->
    <l-dialog
      :title="$t(formTitle)"
      :visible.sync="formVisible"
      :height="600"
      :width="800"
      @ok="handleSave"
      @close="handleCloseForm"
      @opened="handleOpenedForm"
    >
      <!-- 客户跟进 -->
      <follow-up-form
        v-if="formTitle == '客户跟进'"
        ref="followForm"
      />
      <my-form
        v-else
        ref="form"
        f_State="0"
      />
    </l-dialog>

    <l-dialog
      :title="$t(formTitle)"
      :visible.sync="transferVisible"
      :height="100"
      :width="300"
      @ok="transferSave"
      @close="transferCloseForm"
    >
      <div class="form_flex_center">
        <l-user-select
          style="width: 200px; margin-left: 50px; margin-top: 20px"
          :clearable="false"
          v-model="transferList.caseErpCustomerEntity.f_SaleId"
        ></l-user-select>
      </div>
    </l-dialog>
  </l-layout>
</template>

<script>
import MyForm from "./form";
import FollowUpForm from "./followUpForm";

import DetailForm from "./detailForm";

const api = window.$api.erpcase.customer;

export default {
  components: {
    MyForm,
    FollowUpForm,
    DetailForm,
  },
  data() {
    return {
      lr_isPage: true,
      moduleCode: "ERP_Customers",

      // query参数
      queryData: {
        f_Type: "",
        f_Source: "",
        f_Name: "",
      },

      queryItems: [
        { label: "客户类型", prop: "f_Type" },
        { label: "来源", prop: "f_Source" },
        { label: "客户名称", prop: "f_Name" },
        { label: "创建日期", prop: "f_CreateDate" },
      ],

      // 表格参数
      tableLoading: false,
      tableData: [],
      tableTotal: 0,
      tableCurrentPage: 1,
      tablePageSize: 50,
      columns: [
        {
          label: "客户名称",
          prop: "f_Name",
          align: "left",
          dataType: "input",
          width: 200,
          isNotAutoWrap: true,
        },
        {
          label: "客户类型",
          prop: "f_Type",
          align: "left",
          dataType: "mydata",
          options: [
            { value: " 普通客户", label: " 普通客户" },
            { value: "重要客户", label: "重要客户" },
            { value: "SVIP客户", label: "SVIP客户" },
          ],
        },
        {
          label: "联系人",
          prop: "f_DefaultName",
          align: "left",
          dataType: "input",
        },
        {
          label: "手机号码",
          prop: "f_DefaultPhone",
          align: "left",
          dataType: "input",
          width: 120,
        },
        {
          label: "所在行业",
          prop: "f_Industry",
          align: "left",
          dataType: "input",
        },
        {
          label: "来源",
          prop: "f_Source",
          align: "left",
          dataType: "mydata",
          options: [
            { value: "电话销售", label: "电话销售" },
            { value: "主动来电 ", label: "主动来电" },
            { value: "客户介绍", label: "客户介绍" },
            { label: "访问官网", value: "访问官网" },
            { label: "其他途径", value: "其他途径" },
          ],
        },
        {
          label: "归属",
          prop: "f_SaleId",
          align: "left",
          dataType: "user",
          width: 120,
        },
        {
          label: "创建日期",
          prop: "f_CreateDate",
          align: "left",
          dataType: "datetime",
          format: "yyyy-MM-dd",
          width: 120,
        },
        {
          label: "创建人",
          prop: "f_CreateUserName",
          align: "left",
          dataType: "input",
          width: 120,
        },
      ],
      tableBtns: [
        { prop: "FollowUp", label: "跟进" },
        { prop: "Details", label: "Details查看", width: 80 },
        { prop: "Edit", label: "Edit" },
        { prop: "Transfer", label: "转移" },
        { prop: "Delete", label: "Delete" },
      ],

      // 表单参数
      formVisible: false,
      formTitle: "",
      formEditRow: null,
      formEdit: false,

      // Details查看
      showDetails: false,
      show_name: "",
      detailForm: {},

      // 客户转移
      transferList: {
        caseErpCustomerEntity: {
          f_SaleId: "",
        },
      },
      transferVisible: false,
    };
  },
  computed: {
    f_TypeOptions() {
      return [
        { value: "", label: "全部" },
        { value: " 普通客户", label: " 普通客户" },
        { value: "重要客户", label: "重要客户" },
        { value: "SVIP客户", label: "SVIP客户" },
      ];
    },
    f_SourceOptions() {
      return [
        { value: "", label: "全部" },
        { value: "电话销售", label: "电话销售" },
        { value: "主动来电 ", label: "主动来电" },
        { value: "客户介绍", label: "客户介绍" },
        { label: "访问官网", value: "访问官网" },
        { label: "其他途径", value: "其他途径" },
      ];
    },
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.loadTableData();
    },

    handleSearch() {
      this.loadTableData();
    },
    turnTablePage({ rows }) {
      this.tablePageSize = rows;
      this.loadTableData(true);
    },
    async loadTableData(isNotFirst) {
      if (!isNotFirst) {
        this.tableCurrentPage = 1;
      }
      this.tableLoading = true;
      let queryData = this.$deepClone(this.queryData);

      queryData.rows = this.tablePageSize;
      queryData.page = this.tableCurrentPage;
      queryData.sidx = "F_Id";
      queryData.f_State = 0;
      let data = await this.$awaitWraper(api.getPage(queryData));
      if (data != null) {
        this.tableData = data.rows;
        this.tableTotal = data.records;
      } else {
        this.tableData = [];
      }
      this.tableLoading = false;
    },

    handleAdd() {
      this.formEdit = false;
      this.handleShowForm("Add客户");
    },
    handleFollowUp($index, row) {
      this.formEdit = false;
      this.formEditRow = row;
      this.handleShowForm("客户跟进");
    },
    handleEdit($index, row) {
      this.formEdit = true;
      this.formEditRow = row;
      this.handleShowForm("Edit");
    },
    handleDelete($index, row) {
      this.$confirm(
        this.$t("This operation will permanently delete the data. Do you want to continue?"),
        this.$t("Tips"),
        {
          confirmButtonText: this.$t("confirm"),
          cancelButtonText: this.$t("cancel"),
          type: "warning",
        }
      )
        .then(async () => {
          this.tableData.splice($index, 1);
          this.tableTotal--;
          await api.remove(row.f_Id);
          this.$message({
            type: "success",
            message: this.$t("Delete  success"),
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: this.$t("Delete has been canceled!"),
          });
        });
    },
    async handleDetails($index, row) {
      this.showDetails = true;
      this.show_name = "客户Details查看";
      this.detailForm = await this.$awaitWraper(api.get(row.f_Id));
      this.$refs.detailForm.setForm(this.detailForm);
      //    console.log('Details查看',data)
    },
    async handleTransfer($index, row) {
      this.transferList = await this.$awaitWraper(api.get(row.f_Id));
      console.log(this.transferList); // 在此处添加按钮逻辑
      this.formTitle = "客户转移";
      this.transferVisible = true;
    },

    async handleSave(showLoading, hideLoading) {
      showLoading("saving data...");
      if (this.formTitle != "客户跟进") {
        if (await this.$refs.form.validateForm()) {
          const res = await this.$refs.form.saveForm({
            keyValue: this.formEdit ? this.formEditRow.f_Id : "",
            isEdit: this.formEdit,
          });
          if (res) {
            const msg = this.formEdit ? "更新成功!" : "Add成功!";
            this.$message({
              type: "success",
              message: this.$t(msg),
            });
            this.loadTableData();
            this.formVisible = false;
          }
        }
      } else if (this.formTitle == "客户跟进") {
        if (await this.$refs.followForm.validateForm()) {
          const res = await this.$refs.followForm.saveForm({
            isEdit: this.formEdit,
          });
          if (res) {
            const msg = this.formEdit ? "更新成功!" : "Add成功!";
            this.$message({
              type: "success",
              message: this.$t(msg),
            });
            this.loadTableData();
            this.formVisible = false;
          }
        }
      }
      hideLoading();
    },
    // 加入公海
    async handleAddOpens() {
      let data = this.$refs.mainTable.getSelected();

      const idList = data.map((item) => item.f_Id);
      if (idList.length > 0) {
        await this.transfer(idList);
      }
    },
    async transfer(idList) {
      this.$confirm(
        this.$t("此操作会将选中的用户移至客户公海,点击confirm操作成功"),
        this.$t("Tips"),
        {
          confirmButtonText: this.$t("confirm"),
          cancelButtonText: this.$t("cancel"),
          type: "warning",
        }
      )
        .then(async () => {
          let ids = idList.join(",");
          for (let i in this.tableData) {
            console.log("this.tableData", this.tableData[i].f_Id);
            for (let j in idList) {
              if (this.tableData[i].f_Id == idList[j]) {
                this.tableData.splice(i, 1);
              }
            }
          }
          await this.$awaitWraper(api.transferpublic(ids));
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "操作cancel!",
          });
        });
    },
    handleShowForm(text) {
      this.formTitle = text;
      this.formVisible = true;
    },
    async handleOpenedForm(showLoading, hideLoading) {
      if (this.formTitle == "客户跟进") {
        showLoading("Loading data...");
        await this.$refs.followForm.loadFormData({
          keyValue: this.formEditRow.f_Id,
        });
        hideLoading();
      }

      if (this.formEdit) {
        showLoading("Loading data...");
        await this.$refs.form.loadFormData({ keyValue: this.formEditRow.f_Id });
        hideLoading();
      }
    },
    handleCloseForm() {
      if (this.formTitle == "客户跟进") {
        this.$refs.followForm.resetForm();
      } else {
        this.$refs.form.resetForm();
      }
    },
    // 关闭客户转移
    transferCloseForm() {
      this.transferVisible = false;
    },

    // 保存客户转移
    async transferSave() {
      // console.log('Edit保存',this.transferList)
      const list = await this.$awaitWraper(
        api.update(
          this.transferList.caseErpCustomerEntity.f_Id,
          this.transferList
        )
      );
      // console.log('Edit保存', list)
      this.$message({
        type: "success",
        message: list,
      });
      this.loadTableData();
      this.transferVisible = false;
    },
  },
};
</script>
<style>
.custmer .el-input.is-disabled .el-input__inner {
  background-color: transparent !important;
  border-color: transparent !important;
  color: #595959 !important;
}
</style>
